package com.deng.controller;

import com.deng.Service.PaperService;
import com.deng.Service.TagService;
import com.deng.config.AllAttriOfPaper;
import com.deng.config.PaperAndComments;
import com.deng.config.common.Paging;
import com.deng.model.Paper;
import com.deng.model.User;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @Author 邓小熙
 * @Date 2022/5/9 21:13
 * @Version 1.0
 */
@Controller
public class PaperController {
    @Autowired
    PaperService paperService;
    @Autowired
    TagService tagService;
    Logger logger = Logger.getLogger(this.getClass().getName());
//    @RequestMapping(value = "/main/paper/{id}")
//    public String page(@PathVariable("id") int id , HttpServletRequest request){
//        request.setAttribute("page",paperService.findAllAttriOfPaper(id));
//        return "main/page";
//    }
    @RequestMapping(value = "/main/paper/{id}", method = RequestMethod.GET)
    public @ResponseBody
    ModelAndView page(@PathVariable("id") int id) {
        ModelAndView modelAndView = new ModelAndView();
        Map<String, Object> map = Maps.newHashMap();
        //根据id进行mark的增加
//        Paper paper = paperService.findPaperById(id);
        AllAttriOfPaper allAttriOfPaper = paperService.findAllAttriOfPaper(id);
        try {
            map.put("page", paperService.findAllAttriOfPaper(id));
            System.out.println(allAttriOfPaper);
        } catch (Exception e) {
            System.out.println(e);
        }
        modelAndView.addAllObjects(map);
        modelAndView.setViewName("main/page");
        return modelAndView;
    }

    /**
     * 返回文章和评论的信息 按时间排序
     * @return
     */
    @RequestMapping(value = "/main/paper/PapersByTime",method = RequestMethod.POST)
    public @ResponseBody Map<String, List<PaperAndComments>>PapersByTime(){
        return paperService.findAllPapersByTime();
    }
    /**
     * 获得一月内热门文章的json
     * @return
     */
    @RequestMapping(value = "/main/paper/hotPapersInMonth")
    public @ResponseBody PageInfo<Paper> hotPapersInMonth(){
        PageInfo pageInfo = paperService.findPaperInMonth();
//        List<Paper> list = pageInfo.getList();
//        List<Paper> list2 = Lists.newLinkedList();
//        for (Paper p:list){
//        list2.add(0,p);
//        }
//        pageInfo.setList(list2);
        return pageInfo;
    }
    /**
     * 返回文章和评论信息 按热度排序
     * @return
     */
    @RequestMapping(value = "/main/paper/PapersByMark",method = RequestMethod.POST)
    public @ResponseBody
    Map<String,List<PaperAndComments>> paperByMark(){
        return paperService.findAllPapersByMark();
    }
    /**
     * 得到前一篇和下一片的内容
     * @param paperId
     * @return
     */
    @RequestMapping(value = "/main/paper/PreAndNextPage/{paperId}")
    public @ResponseBody Map<String ,Object> findPreAndNextPage(@PathVariable("paperId") int paperId){
        Map<String,Object> map = paperService.findPreAndNextPage(paperId);
        return map;
    }
    /**
     * 个人页面所有文章
     * @param pageNum
     * @param search
     * @param name
     * @return
     */
    @RequestMapping(value = "/main/paper/personalPaperList/{name}/{pageNum}")
    public @ResponseBody PageInfo<Paper> personalPaperList(@PathVariable("pageNum") int pageNum
            ,@RequestParam(value = "search",required = false) String search
            ,@PathVariable("name")String name){
        return paperService.findPaperByUserName(name,pageNum,search);
    }
    /**
     *   文章库
     * @param pageNum
     * @param search
     * @return
     */
    @RequestMapping(value = "/main/paper/test/{pageNum}")
    public @ResponseBody
    PageInfo pageTest(
            @PathVariable(value = "pageNum") int pageNum,
            @RequestParam(value = "search", required = false) String search){
        Map<String,Object> map = Maps.newHashMap();
//        PageHelper.startPage(pageNum, Paging.LIMIT.getValue());
        PageInfo pageInfo = paperService.findAllPapers(search,pageNum);
        System.out.println(pageInfo.getPageSize());
        map.put("pageInfo",pageInfo.getPageSize());
        map.put("pageNum",pageNum);
        return pageInfo;
    }

//    @RequestMapping("/list")
//    public String getList(@RequestParam(value = "pageNum",defaultValue = "1") int pageNum, Map<String,Object> map){
////        PageInfo<Paper> page = userService.getLists(pageNo);
//        PageInfo<Paper> page = paperService.findAllPapersByPageInfo(pageNum);
//        map.put("page",page);
//        return "main/pageList";  //转发到你自己的页面
//    }

    /**
     * 后台文章管理页面
     * @param url
     * @return
     */
    @RequestMapping(value = "/manage/pageMes")
    public ModelAndView pageManage(String url){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("InnerLayui/pageMes");
        Map<String,Object> map = Maps.newHashMap();
        map.put("url",url);
        modelAndView.addAllObjects(map);
        return modelAndView;
    }
    /**
     * 根据名字查询文章
     * @param name
     * @param pageNum
     * @return
     */
    @RequestMapping(value = "/paper/findPaperByName/{name}/{pageNum}")
    public @ResponseBody Map<String,Object> findPaperByName(
            @PathVariable("name") String name, @PathVariable("pageNum") String pageNum){
        int limit = Paging.LIMIT.getValue();
        Map<String ,Object> map = paperService.findPaperByUser(name,pageNum);
        map.put("pageNum",pageNum);
        map.put("limit", limit);
        return map;
    }
    /**
     * 返回修改文章内容页面
     * @param id
     * @return
     */
    @RequestMapping("/updatePageContent/{id}")
    public ModelAndView updatePageContent(@PathVariable("id") int id){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("paper",paperService.findPaperById(id));
        modelAndView.setViewName("InnerLayui/caozuo/UpdatemarkDown");
        return modelAndView;
    }
    /**
     * 更新文章内容
     * @param id
     * @param content
     * @return
     */
    @RequestMapping(value = "/paper/updateContent/{id}")
    public @ResponseBody int updateContent(@PathVariable("id") String id,String content){
        return paperService.updatePaperContentById(content,id);
    }
    /**
     * 删除
     * @param id 文章的id
     * @return
     */
    @RequestMapping(value = "/paper/delect/{id}",method = RequestMethod.POST)
    public @ResponseBody
    int deletePaperByPaperId(@PathVariable("id") int id){
        int hasTag = tagService.findHasTagByPaperId(id);
        checkPaperHasTag(hasTag,id);
        return paperService.deletePaperByPaperId(id);
    }

    /**
     * 检查文章中是否有tag 有就删除
     * @param hasTag
     * @param id
     */
    private void checkPaperHasTag(int hasTag,int id){
        if(hasTag!=0){
            logger.info("文章里面有Tag 准备删除tag");
            try{
                tagService.delectTag(id);
            }catch (Exception e){
                logger.info("删除过程出错");
            }
            logger.info("删除文章的tag 成功");
        }
        else {
            logger.info("这个paper没有tag");
        }
    }


    /**
     * 返回admin文章审核页面
     *
     */
    @RequiresPermissions("can_manage")
    @RequestMapping(value = "/paper/adminPapers",method = RequestMethod.GET)
    public ModelAndView returnAdminPapers(@RequestParam(value = "url",required = false) String url){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("url",url);
        modelAndView.setViewName("InnerLayui/admin/pageReview");
        return modelAndView;
    }
    /**
     * 后台文章管理的数据
     * @param pageNum 当前页数
     * @param timePick 时间选择
     * @param search 查询关键字
     * @return所有文章的数据
     */
    @RequestMapping(value = {"/paper/adminPapersData/{pageNum}","/paper/adminPapersData/{pageNum}/{timePick}"})
    public @ResponseBody Map<String,Object> adminPapers(
            @PathVariable(value = "pageNum") int pageNum,
            @PathVariable(value = "timePick",required = false) String timePick,
            @RequestParam(value = "title",required = false) String search){
        return paperService.findPapers(pageNum,search,timePick);
    }
    /**
     * 返回修改文章状态页面
     * @param id
     * @return
     */
    @RequestMapping(value = "/paper/FixPaperStatues/{id}",method = RequestMethod.GET)
    public ModelAndView returnFixPaperStatues(@PathVariable(value = "id") int id){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("paperId",id);
        modelAndView.setViewName("InnerLayui/admin/caozuo/updatePageStatus");
        return modelAndView;
    }
    /**
     * 更改文章状态执行方法
     * @param review 输入状态 string类型
     * @param id 文章id
     * @return
     */
    @RequestMapping(value = "/paper/updatePaperStatus/{id}")
    public @ResponseBody int updatePaperStatus(
            @RequestParam(value = "review") String review,
            @PathVariable(value = "id") int id){
        return paperService.updatePaperStatus(id, review);
    }


    /**
     * 编辑页面
     * @param content
     * @return
     */
    @RequestMapping("/newPage")
    public String markDown(
            @RequestParam(value = "content",required = false) String content){
        return "markDown";
    }
    /**
     * 返回新建文章的提交页面
     * @return
     */
    @RequestMapping("/newPage/submit")
    public String newPageSubmit(){
        return "InnerLayui/submit";
    }
}